//
//  AppDelegate.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/9.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,JPUSHRegisterDelegate,BMKLocationAuthDelegate,BMKGeneralDelegate {

    var window: UIWindow?

    var mapManager:BMKMapManager?
    
    //远程推送处理器。true表示有未读推送，false表示已读
    var remoteNotificationHandler:((Bool) -> Void)?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        SVProgressHUD.setForegroundColor(UIColor(white: 1, alpha: 1))
        SVProgressHUD.setBackgroundColor(UIColor(white: 0.15, alpha: 0.85))
        SVProgressHUD.setDefaultMaskType(.none)//允许交互
        
        self.mapManager = BMKMapManager()
    BMKLocationAuth.sharedInstance().checkPermision(withKey: LCBaiduMapKey, authDelegate: self)
        let ret = self.mapManager?.start(LCBaiduMapKey, generalDelegate: nil)
        if ret ==  false {
           
        }
        Bugly.start(withAppId: "9ee96ba6bc")
        //启用键盘管理工具
        self.startIQKeyboardManager()
        
        //配置jpush
        self.startJPush(launchOptions)
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.backgroundColor = UIColor.white
        //        let nav = UINavigationController(rootViewController: ViewController())
        /***是否第一次使用***/
        if isFirstUse() {
            let introVC = IntroViewController()
            self.window?.rootViewController = introVC
            self.window?.makeKeyAndVisible()
        }
        else {
            if LoginType == -1{
                let vc = LoginViewController()
                self.window?.rootViewController = vc
                self.window?.makeKeyAndVisible()
            }else if LoginType == 1{
                LoginAuthenticationService.setupIsRangeData(range: "2")
                let rootVC = WWTabBarController()
                self.window?.rootViewController = rootVC
                self.window?.makeKeyAndVisible()
            }else if LoginType == 2{
                let rootVC = ContractorLoginViewController(nibName: "ContractorLoginViewController", bundle: nil)
                self.window?.rootViewController = rootVC
                self.window?.makeKeyAndVisible()
            }
            
        }
        return true
    }
    
    func stopIQKeyboardManager(){
        let manager = IQKeyboardManager.sharedManager()
        manager.enable = false
    }

    func startIQKeyboardManager() {
        let manager = IQKeyboardManager.sharedManager()
        manager.enable = true
        manager.keyboardDistanceFromTextField = 1
        manager.shouldResignOnTouchOutside = true
        manager.shouldToolbarUsesTextFieldTintColor = true
        manager.toolbarDoneBarButtonItemText = "确认"
        manager.enableAutoToolbar = true
    }
    /**************百度地图代理方法******************/
    
    func onCheckPermissionState(_ iError: BMKLocationAuthErrorCode) {
        
        print("授权状态")
        print(iError)
    }
    func onGetPermissionState(_ iError: Int32) {
        if 0==iError{
            print("授权成功")
        }else{
            print("授权失败")
        }
        
    }
    func onGetNetworkState(_ iError: Int32) {
        if 0==iError{
            print("联网成功")
        }else{
            print("联网失败")
        }
        
    }
    /********JPush*********/
    
    func startJPush(_ launchOptions:[UIApplicationLaunchOptionsKey: Any]?) {
        //初始化APNS。      初始化成功
        let entity = JPUSHRegisterEntity()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.sound.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        //初始化JPush
        JPUSHService.setup(withOption: launchOptions, appKey: "42024d28d7679adb3570b2fd", channel: "颤抖吧！凡人", apsForProduction: true, advertisingIdentifier: nil)
    }

    
    //MARK:JPUSHRegisterDelegate
    //前台得到的的通知对象
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let userInfo = notification.request.content.userInfo
        print(userInfo)
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        //执行这个方法来选择是否提示用户。默认在前台收到推送是不提示用户的
    completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue | UNNotificationPresentationOptions.sound.rawValue))
        
        if let handler = self.remoteNotificationHandler {
            handler(true)
        }
    }
    //通知对象被点击
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        //系统要求执行这个方法
        completionHandler()
RemoteNotificationHandleService.handleRemoteNotificationWhenClick(userInfo)
    }
    
    //初始化APNS成功，上报deviceToken
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }
    //初始化APNS失败，提升一下
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
       
    }
    
    // 非IOS10情况下：1.点击推送会调用。2.前台收到推送会调用。3.如果包含content-available，后台收到推送会调用
    // IOS10情况下：1.如果包含content-available，前台收到推送会调用。2.如果包含content-available，后台收到推送会调用
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if let handler = self.remoteNotificationHandler {
            handler(true)
        }
        completionHandler(.noData)
        
        /*几种情况说明---含有content-available的情况下：
             IOS10版本：
         1.后台收到推送会调用，state==.background
         2.前台收到推送会调用，state==.active
         3.程序杀死情况，收到推送，点击图标进入。不会调用这个方法
         4.程序杀死情况，收到推送，点击推送进入。不会调用这个方法
         5.IOS10情况下，任何状态下点击推送或者图标，都不会调用这个方法
         
             非iOS10版本：
         1.前台收到推送会调用，state==.active
         2.后台收到推送会调用。state==.background
         3.后台情况下点击推送回调用。state==.inactive
         4.杀死情况下点击图标进入app。不会调用
         5.杀死情况下点击推送进入app会调用。state==.inactive
         
         我要考虑的：
             非IOS10：
         1.前台收到要弹框，在这个方法里处理
         2.后台收到要弹框，在这个方法里处理
         3.点击推送不处理
             IOS10：
         1.前台收到要弹框，在这个方法里处理
         2.后台收到要弹框，在这个方法里处理
         3.点击推送不处理
         */

        switch application.applicationState {
        case .active,.background:
            RemoteNotificationHandleService.handleRemoteNotification(userInfo)
            //IOS10以上时，点击推送不会走这个方法。但是iOS10以下会走这个方法，这种情况下状态是inactive
        case .inactive:
        RemoteNotificationHandleService.handleRemoteNotificationWhenClick(userInfo)
        }
    }
    
    //设置app别名
//    func setAppAlias(_ accountId: String?) {
//
//        if accountId == nil {
//            JPUSHService.deleteAlias({ (iResCode, iAlias, seq) in
//                if iResCode == 0 {
//                    //删除别名成功
//                }
//                else {
//                    print("删除推送alias失败")
//                }
//            }, seq: 1024)
//        }
//        else {
//            let tempString = accountId!.replacingOccurrences(of: "-", with: "")
//            print(tempString)
//            JPUSHService.setAlias(tempString, completion: { (iResCode, iAlias, seq) in
//                if iResCode == 0 {
//                    //设置别名成功
//                }
//                else {
//                    print("设置推送alias失败")
//                }
//            }, seq: 1024)
//        }
//        
//        if accountId == nil {
//            
//        }
//        
//    }
//    
    //设置标签
    func setTags(_ accountId: String?) {
        if accountId == nil {
            JPUSHService.cleanTags({ (iResCode, iTags, seq) in
                if iResCode == 0{
                    
                }
                else {
                    
                }
            }, seq: 1024)
        }
        else {
            let tempString = accountId!.replacingOccurrences(of: "-", with: "")
            
            JPUSHService.setTags([tempString], completion: { (iResCode, iTags, seq) in
                if iResCode == 0 {
                    
                }
                else {
                    
                }
            }, seq: 1024)
        }
    }

    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        let value = UserDefaults.standard.bool(forKey: "isReceive")
        if value == false {
           
        }
        else {
           
            UserDefaults.standard.setValue(false, forKey: "isReceive")
        }
        if LoginType == -1 {
            
        }else if LoginType == 1 {
            //每次从后台进入前台就检查登录状态，如果登入状态改变就通过下面的方式进入登录界面
            LoginAuthenticationService.verifyLoginStatus { (response) in
                if !response.success {
                    
                    let previousRootViewController = self.window?.rootViewController
                    self.window?.rootViewController = LoginViewController()
                    for view in self.window!.subviews {
                        if let viewClass = NSClassFromString("UITransitionView") {
                            if view.isKind(of: viewClass) {
                                view.removeFromSuperview()
                            }
                        }
                    }
                    previousRootViewController?.dismiss(animated: false, completion: {
                        previousRootViewController?.view.removeFromSuperview()
                    })
                }else{
                    let center = NotificationCenter.default
                    let notificationName = NSNotification.Name.init(MWNotificationMainRefresh)
                    center.post(name: notificationName, object: nil, userInfo: nil)
                }
            }
        }else if LoginType == 2{
            LCLoginNetWork.login(username:ContractorName ?? "", password: ContractorPass ?? "") { (response) in
                if response.success {
                    //WWEndLoading()
                }
                
            }
        }
        
        
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

